package com.hboxs.asl.controller.app.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Product;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Set;

/**
 * Created by xxx on 2016/12/06
 */
@Controller(value = "appMemberFavorController")
@RequestMapping(value = "/app/m/favor")
public class FavorControl extends BaseController {

    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "memberServiceImpl")
    private MemberService memberService;

    /**
     * 收藏或取消收藏商品
     *
     * @param pId 商品id
     * @return JsonMessage
     */
    @RequestMapping(value = "/change", method = RequestMethod.GET)
    public
    @ResponseBody
    Object changeFavor(Long pId) {
        try {
            Product product = productService.find(pId);
            if (product == null) {
                return JsonMessage.error("该商品不存在");
            }
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }
            String message = "favor";
            Set<Product> products = member.getFavoriteProducts();
            if (products.contains(product)) {
                products.remove(product);
                message = "unfavor";
            } else {
                products.add(product);
            }

            memberService.update(member);
            return JsonMessage.success(message);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 我的收藏
     *
     * @return json
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage myFavorite() {
        try {
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Set<Product> fProducts = member.getFavoriteProducts();

            return JsonMessage.success(
                    JsonMessage.optimiseObj(
                            fProducts, "id", "image", "name", "price", "promotionPrice", "finalScore", "weight", "sales"
                    )
            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    //TODO:清空收藏
}
